package com.bigfans.framework.jms;

import java.lang.reflect.Constructor;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSContext;
import javax.jms.JMSException;

import com.bigfans.framework.utils.StringHelper;

public class JmsConnectionFactory implements ConnectionFactory {

	public static final String DELEGATE_ACTIVEMQ = "activemq";
	public static final String ACTIVEMQFACTORY_CLASS = "org.apache.activemq.ActiveMQConnectionFactory";

	private ConnectionFactory delegate;

	public JmsConnectionFactory(String userName, String password, String brokerURL) {
		this(DELEGATE_ACTIVEMQ, userName, password, brokerURL);
	}

	public JmsConnectionFactory(String delegateKey, String userName, String password, String brokerURL) {
		// 默认使用activeMQ作为jms中间件
		if (delegateKey.equals(DELEGATE_ACTIVEMQ) || StringHelper.isEmpty(delegateKey)) {
			try {
				Class<?> factoryClass = Class.forName(ACTIVEMQFACTORY_CLASS);
				Constructor<?> constructor = factoryClass.getConstructor(String.class, String.class, String.class);
				constructor.setAccessible(true);
				delegate = (ConnectionFactory) constructor.newInstance(userName, password, brokerURL);
			} catch (Exception e) {
				e.printStackTrace();
			}
			// delegate = new ActiveMQConnectionFactory(userName, password,
			// brokerURL);
		} else {
			throw new RuntimeException("不支持当前JMS中间件:" + delegateKey);
		}
	}

	public Connection createConnection() throws JMSException {
		return delegate.createConnection();
	}

	public Connection createConnection(String userName, String password) throws JMSException {
		return delegate.createConnection(userName, password);
	}

	public JMSContext createContext() {
		return delegate.createContext();
	}

	public JMSContext createContext(String userName, String password) {
		return delegate.createContext(userName, password);
	}

	public JMSContext createContext(String userName, String password, int sessionMode) {
		return delegate.createContext(userName, password, sessionMode);
	}

	public JMSContext createContext(int sessionMode) {
		return delegate.createContext(sessionMode);
	}

}
